let app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        totalWarning: 0,
        groupUserList: [],
        showShare: false,
        switchChecked: true,
        chooseGroupId: null,
        title: null,
        showChooseTitle: false,
        columns: [''],
        columnsInfo: [''],
        optionList: [],
        movableViewInfo: {
            y: 0,
            showClass: 'none',
            data: {}
        },
        pageInfo: {
            rowHeight: 47,
            scrollHeight: 85,
            startIndex: null,
            scrollY: true,
            readyPlaceIndex: null,
            startY: 0,
            selectedIndex: null,
        },
        write_kind_list: [{
            word: '支出',
            choose: true,
            type: 0
        },
        {
            word: '入账',
            choose: false,
            type: 1
        }
        ],
        kind_list_out: [],
        kind_list_in: [],
        ColorMost: app.globalData.ColorMost,
        configColor: app.globalData.configColor,
        configColorForOnlyStyle: app.globalData.configColorForOnlyStyle,
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
    },
    changeShare() {
        wx.request({
            url: app.globalData.url + '/updateMyGroupShare',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
                groupId: this.data.chooseGroupId,
                share: this.data.switchChecked ? 0 : 1
            },
            success: (res) => {
                this.setData({
                    switchChecked: res.data.data == 1,
                });
            }
        })
    },
    toggle(event) {
        let that = this
        let userId = event.currentTarget.dataset.index
        wx.showModal({
            title: '是否确认同步?',
            content: '同步后该账本的所有类别将会被覆盖!',
            success(res) {
                if (res.confirm) {
                    wx.request({
                        url: app.globalData.url + '/syncGroupCategory',
                        method: 'GET',
                        data: {
                            syncUserId: userId,
                            userId: wx.getStorageSync('userInfo').id,
                            groupId: that.data.chooseGroupId
                        },
                        success: (res) => {
                            let responseData = res.data
                            if (responseData.flag) {
                                that.onClose()
                                that.created(true)
                                wx.showToast({
                                    title: '同步成功',
                                    icon: 'success'
                                })
                            } else {
                                wx.showToast({
                                    title: '同步失败:' + responseData.message,
                                    icon: 'none'
                                })
                            }
                        },
                        fail: (err) => {
                            console.log('失败', err);
                        }
                    })
                }
            }
        })
    },
    // 打开共享设置
    showShare() {
        wx.request({
            url: app.globalData.url + '/getGroupUser',
            method: 'GET',
            data: {
                id: this.data.chooseGroupId,
            },
            success: (res) => {
                console.log(res.data.data)
                if (res.data.flag) {
                    let groupUserList = []
                    res.data.data.forEach(item => {
                        if (item.id == wx.getStorageSync('userInfo').id) {
                            return
                        }
                        groupUserList.push(item)
                    })
                    this.setData({
                        showShare: true,
                        groupUserList: groupUserList
                    });
                }
            }
        })
        wx.request({
            url: app.globalData.url + '/getMyGroupShare',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
                groupId: this.data.chooseGroupId,
            },
            success: (res) => {
                this.setData({
                    switchChecked: res.data.data == 1,
                });
            }
        })
    },
    onChangeTitle(event) {
        const { picker, value, index } = event.detail;
        // 记油耗
        if (index != 0) {
            this.setData({
                chooseGroupId: this.data.columnsInfo[index].id,
                title: value
            });
            this.created(true);
            this.onClose()
        }
    },
    onClose() {
        this.setData({
            showChooseTitle: false,
            showShare: false
        });
        let that = this
        setTimeout(function () {
            that.setData({
                columns: [''],
                columnsInfo: ['']
            });
        }, 200);

    },
    openChooseTitle() {
        wx.request({
            url: app.globalData.url + '/getGroupByUser',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                if (res.data.flag) {
                    let columnsTemp = this.data.columns
                    let columnsInfoTemp = this.data.columnsInfo
                    res.data.data.forEach((item) => {
                        if (item.active != 2) {
                            return
                        }
                        columnsTemp.push(item.name)
                        columnsInfoTemp.push(item)
                    })
                    this.setData({
                        columns: columnsTemp,
                        columnsInfo: columnsInfoTemp,
                        showChooseTitle: true
                    })
                }
            }
        })
    },
    dragStart: function (event) {
        var startIndex = event.currentTarget.dataset.index

        // 初始化页面数据
        var pageInfo = this.data.pageInfo
        pageInfo.startY = event.touches[0].clientY
        pageInfo.readyPlaceIndex = startIndex
        pageInfo.selectedIndex = startIndex
        pageInfo.scrollY = false
        pageInfo.startIndex = startIndex
        this.setData({
            // 'movableViewInfo.y': pageInfo.startY - (pageInfo.rowHeight / 2)
            'movableViewInfo.y': pageInfo.startY - (pageInfo.rowHeight / 2),
            pageInfo: pageInfo
        })
        // 初始化拖动控件数据
        var movableViewInfo = this.data.movableViewInfo
        movableViewInfo.data = this.data.optionList[startIndex]
        movableViewInfo.showClass = "inline"

        this.setData({
            movableViewInfo: movableViewInfo
        })
    },
    dragMove: function (event) {
        var optionList = this.data.optionList
        var pageInfo = this.data.pageInfo
        var movableViewInfo = this.data.movableViewInfo
        // 计算拖拽距离
        var movedDistance = event.touches[0].clientY - pageInfo.startY
        movableViewInfo.y = pageInfo.startY - (pageInfo.rowHeight / 2) + movedDistance
        //   console.log('移动的距离为', movedDistance)

        // 修改预计放置位置
        var movedIndex = parseInt(movedDistance / pageInfo.rowHeight)
        var movedIndex = Math.round(movedDistance / pageInfo.rowHeight)
        var readyPlaceIndex = pageInfo.startIndex + movedIndex
        if (readyPlaceIndex < 0) {
            readyPlaceIndex = 0
        }
        else if (readyPlaceIndex >= optionList.length) {
            readyPlaceIndex = optionList.length - 1
        }

        if (readyPlaceIndex != pageInfo.selectedIndex) {
            var selectedData = optionList[pageInfo.selectedIndex]

            optionList.splice(pageInfo.selectedIndex, 1)
            optionList.splice(readyPlaceIndex, 0, selectedData)
            pageInfo.selectedIndex = readyPlaceIndex
        }
        // 移动movableView
        pageInfo.readyPlaceIndex = readyPlaceIndex

        this.setData({
            movableViewInfo: movableViewInfo,
            optionList: optionList,
            pageInfo: pageInfo
        })
    },
    dragEnd: function (event) {

        // 重置页面数据
        var pageInfo = this.data.pageInfo
        pageInfo.readyPlaceIndex = null
        pageInfo.startY = null
        pageInfo.selectedIndex = null
        pageInfo.startIndex = null
        pageInfo.scrollY = true
        // 隐藏movableView
        var movableViewInfo = this.data.movableViewInfo
        movableViewInfo.showClass = 'none'

        this.setData({
            pageInfo: pageInfo,
            movableViewInfo: movableViewInfo
        })

        if (this.data.write_kind_list[0].choose) {
            this.setData({
                kind_list_out: this.data.optionList
            })
        } else {
            this.setData({
                kind_list_in: this.data.optionList
            })
        }
        wx.request({
            url: app.globalData.url + '/updateCategorySort',
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                groupId: this.data.chooseGroupId,
                outCategory: this.data.kind_list_out,
                inCategory: this.data.kind_list_in
            },
            success: (res) => {
                let responseData = res.data
                if (!responseData.flag) {
                    wx.showToast({
                        title: '查询失败，请稍后尝试',
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },
    go_my() {
        wx.switchTab({
            url: '/pages/my/my',
        });
    },
    // 选择支出或者入账
    choose_type(e) {
        let write_kind_list = this.data.write_kind_list
        write_kind_list.forEach((item) => {
            item.choose = false
        })
        let index = e.currentTarget.dataset.index * 1
        write_kind_list[index].choose = true
        this.setData({
            write_kind_list
        })

        if (write_kind_list[0].choose) {
            this.setData({
                optionList: this.data.kind_list_out
            })
        } else {
            this.setData({
                optionList: this.data.kind_list_in
            })
        }

        let totalWarning = 0;
        this.data.optionList.forEach(item => {
            totalWarning += item.warningNum || 0;
        });
        this.setData({
            totalWarning: totalWarning
        })
    },
    add_category() {
        wx.navigateTo({
            url: '/pages/category_opt/category_opt?isOut=' + this.data.write_kind_list[0].choose + '&chooseGroupId=' + this.data.chooseGroupId + '&chooseGroupName=' + this.data.title
        })
    },
    delete(e) {
        let isOut = false
        if (this.data.write_kind_list[0].choose) {
            isOut = true
        }
        let that = this
        wx.showModal({
            title: '',
            content: '是否确认删除',
            success(res) {
                if (res.confirm) {
                    wx.request({
                        url: app.globalData.url + '/delCategory',
                        method: 'GET',
                        data: {
                            id: e.currentTarget.dataset.id,
                            userId: wx.getStorageSync('userInfo').id,
                            groupId: that.data.chooseGroupId,
                            isOut: isOut
                        },
                        success: (res) => {
                            let responseData = res.data
                            if (responseData.flag) {
                                that.created(that.data.write_kind_list[0].choose)
                                wx.showToast({
                                    title: '删除成功',
                                    icon: 'success'
                                })
                            } else {
                                wx.showToast({
                                    title: '删除失败:' + responseData.message,
                                    icon: 'none'
                                })
                            }
                        },
                        fail: (err) => {
                            console.log('失败', err);
                        }
                    })
                } else if (res.cancel) {
                    //   console.log('用户点击取消')
                }
            }
        })

    },
    showDetail(event) {
        let row = this.data.optionList[event.currentTarget.dataset.index]
        row.isOut = this.data.write_kind_list[0].choose
        wx.navigateTo({
            url: '/pages/category_opt/category_opt?chooseGroupName=' + this.data.title + '&chooseGroupId=' + this.data.chooseGroupId + '&row=' + JSON.stringify(row)
        })
    },
    created(isOut) {
        wx.request({
            url: app.globalData.url + '/getCategoryByGroupId',
            method: 'GET',
            data: {
                groupId: this.data.chooseGroupId,
                userId: wx.getStorageSync('userInfo').id
            },
            success: (res) => {
                let responseData = res.data
                if (responseData.flag) {
                    let categoryList
                    let write_kind_list = this.data.write_kind_list
                    write_kind_list.forEach((item) => {
                        item.choose = false
                    })
                    if (isOut) {
                        write_kind_list[0].choose = true
                        categoryList = responseData.data.outCategory
                    } else {
                        write_kind_list[1].choose = true
                        categoryList = responseData.data.inCategory
                    }

                    let totalWarning = 0;
                    categoryList.forEach(item => {
                        totalWarning += item.warningNum || 0;
                    });

                    this.setData({
                        write_kind_list,
                        kind_list_out: responseData.data.outCategory,
                        kind_list_in: responseData.data.inCategory,
                        optionList: categoryList,
                        totalWarning: totalWarning
                    })
                } else {
                    wx.showToast({
                        title: '查询失败，请稍后尝试',
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let chooseGroupId = wx.getStorageSync('userInfo').groupVO.id
        let title = wx.getStorageSync('userInfo').groupVO.name
        let isOut = true
        if (options.chooseGroupId && options.chooseGroupName) {
            // 从新增页面返回
            chooseGroupId = options.chooseGroupId
            title = options.chooseGroupName
            isOut = typeof options.isOut === 'string'
                ? options.isOut.toLowerCase() === 'true'
                : Boolean(options.isOut);
        }
        this.setData({
            chooseGroupId: chooseGroupId,
            title: title
        })
        this.created(isOut);
    },
    onShow: function () {
        // 切换主题颜色
        if (wx.getStorageSync('ColorMost') !== this.data.ColorMost
            || wx.getStorageSync('configColor') !== this.data.configColor
            || wx.getStorageSync('configColorForOnlyStyle') !== this.data.configColorForOnlyStyle) {
            this.setData({ configColor: wx.getStorageSync('configColor') });
            this.setData({ configColorForOnlyStyle: wx.getStorageSync('configColorForOnlyStyle') });
            this.setData({ ColorMost: wx.getStorageSync('ColorMost') });
        }
    }

})